//
//  ConsultList.m
//  安好
//
//  Created by lianchuang on 14/10/30.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "ConsultList.h"
#import "FMDatabaseAdditions.h"

@implementation ConsultList
/**
 *  本来是初始化数据库，咨询列表的字段，现在未用；可根据自己情况适当用；
 *
 *  @param uid
 *  @param myuid
 *  @param date
 *  @param dateline
 *  @param message
 *  @param qid
 *  @param type
 *  @param noread
 *  @param username
 *  @param method
 *  @param success
 *
 *  @return
 */
- (id)initWithUid:(NSString *)uid AndMyuid:(NSString *)myuid AndDate:(NSString *)date AndDateline:(NSString *)dateline AndMessage:(NSString *)message AndQid:(NSString *)qid AndType:(NSString *)type AndNoread:(NSString *)noread AndUsername:(NSString *)username AndMethod:(NSString *)method And:(NSString *)success
{
    if (self=[super init]) {
        self.qid=qid;
        self.myuid=myuid;
        self.date=date;
        self.dateline=dateline;
        self.message=message;
        self.type=type;
        self.uid=uid;
        self.noread=noread;
        self.username=username;
        self.method=method;
        self.success=success;
    }
    return self;
}
/**
 *  插入或更新咨询列表
 *
 *  @param message          发送消息类型（图片，文字，语音）；
 *  @param readStatus       阅读状态（待回复、已回复、新回复）；
 *  @param success          存入数据库状态；
 *  @param messageDirection 信息方向（发出的、收到的）。
 *
 *  @return     插入或更新咨询列表是否成功
 */
+(BOOL)updateConsultList:(id)message withReadStatus:(NSString *)readStatus withSuccess:(NSString *)success withMessageDirection:(NSString *)messageDirection;
{
    FMDatabase *db=[MyFMDB openDB];
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid1 = [userDefaults objectForKey:@"SelfUidKey"];
    NSString *noread;
    if ([self isExistItem:dict AndDb:db]) {
        NSString * readsql = [NSString stringWithFormat:@"select noread from ConsultList where qid = ?"];
        FMResultSet * rs = [db executeQuery:readsql, [dict valueForKey:@"qid"]];
        if([rs next])
        {
            noread=[rs stringForColumn:@"noread"];
        }
        NSString * sql = [NSString stringWithFormat:@"update ConsultList set date = ?, dateline = ?, message = ?, uid = ?, type = ?, noread = ?, username = ?, method = ?, myuid = ?,success=? where qid = ?"];
        NSString *uid=[dict valueForKey:@"uid"];
        NSString *myuid=uid1;
        NSString *date=@"";
        NSString *dateline=[dict valueForKey:@"dateline"];
        NSString *type=[dict valueForKey:@"type"];
        NSString *qid=[dict valueForKey:@"qid"];
//        NSString *consultType=[dict valueForKey:@"consultType"];
        NSString *username=[dict valueForKey:@"username"];
        if ([messageDirection isEqualToString:@"1"]&&[noread isEqualToString:@"-1"]) {
            readStatus=@"-1";
        }else if([messageDirection isEqualToString:@"1"]&&[noread isEqualToString:@"0"])
        {
            readStatus=@"0";
        }else if ([messageDirection isEqualToString:@"2"])
        {
            noread=readStatus;
        }
        NSString *method=[dict valueForKey:@"method"];
        NSString *chatMessage;
        //    NSInteger messageType;
        if ([[dict valueForKey:@"message"] length] > 0) {
            //        messageType = 1;
            chatMessage=[dict valueForKey:@"message"];
        } else if ([[dict valueForKey:@"pic"] length] > 0) {
            //        messageType = 2;
            chatMessage = @"[图片]";
        } else{
            //        messageType = 3;
            chatMessage = @"[语音]";
        }
//        NSString *departmentname=[dict valueForKey:@"departmentname"];

        NSString *successType=success;

        BOOL successM= [db executeUpdate:sql,date,dateline,chatMessage,uid,type,noread,username,method,myuid,successType,qid];
        MyNSLog("1-2-3-%d",successM);
        return successM;

    }else
    {
        NSString * sql = [NSString stringWithFormat:@"insert into ConsultList (uid, myuid, date, dateline, message, type, qid, username,method,noread,success,departmentname,consultType) values (?, ?, ?, ?, ?, ?, ?, ?, ? ,?,?,?,?)"];
        NSString *uid=[dict valueForKey:@"uid"];
        NSString *myuid=uid1;
        NSString *date=@"";
        NSString *dateline=[dict valueForKey:@"dateline"];
        NSString *type=[dict valueForKey:@"type"];
        NSString *qid=[dict valueForKey:@"qid"];
        NSString *username=[dict valueForKey:@"username"];
        NSString *noread=readStatus;
        NSString *method=[dict valueForKey:@"method"];
        NSString *chatMessage;
        NSString *consultType=[dict valueForKey:@"consultType"];

        if ([[dict valueForKey:@"message"] length] > 0) {
            chatMessage=[dict valueForKey:@"message"];
        } else if ([[dict valueForKey:@"pic"] length] > 0) {
            chatMessage = @"[图片]";
        } else {
            chatMessage = @"[语音]";
        }
        NSString *successType=success;
        NSString *departmentname=[dict valueForKey:@"departmentname"];
        BOOL successM= [db executeUpdate:sql,uid,myuid,date,dateline,chatMessage,type,qid,username,method,noread,successType,departmentname,consultType];
        return successM;
    }
}
/**
 *  根据qid，设置医患信息未读个数
 *
 *  @param qid 患者咨询时，问题id
 *
 *  @return 是否设置医患信息未读个数成功
 */
+(BOOL)resetUnreadCountWithUid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    NSString * sql = [NSString stringWithFormat:@"update ConsultList set noread = 0 where qid = %@", qid];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
/**
 *  判断该问题是否存在
 *
 *  @param dict     聊天的信息
 *  @param dataBase 当前数据库
 *
 *  @return 问题存在的状态
 */
+(BOOL)isExistItem:(NSDictionary *)dict AndDb:(FMDatabase *)dataBase
{
    NSString * sql = [NSString stringWithFormat:@"select qid from ConsultList where qid = ?"];
    FMResultSet * rs = [dataBase executeQuery:sql, [dict valueForKey:@"qid"]];
    if([rs next])
    {
        // 如果有值
        return YES;
    }
    return NO;
}
/**
 *  若消息未发送成功，重新设置
 *
 *  @param qid = 问题id
 *
 *  @return 是否更改成功
 */
- (BOOL)resetConsultListSuccessStatus:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    
    NSString * sql = [NSString stringWithFormat:@"update ConsultList set success = YES where qid = %@", qid];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
/**
 *  获取所有的咨询列表
 *
 *  @return 咨询列表数组
 */
+(NSMutableArray *)readAllConsultList;
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from consultList where myuid = %@ order by dateline desc", uid];
    FMResultSet *rs=[db executeQuery:sql];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    while ([rs next]) {
        //        NSDictionary *rs=[set resultDictionary];
        ConsultList * consultList = [[ConsultList alloc] init];
        consultList.uid = [rs stringForColumn:@"uid"];
        consultList.date = [rs stringForColumn:@"date"];
        consultList.dateline = [rs stringForColumn:@"dateline"];
        consultList.message = [rs stringForColumn:@"message"];
        consultList.qid = [rs stringForColumn:@"qid"];
        consultList.type = [rs stringForColumn:@"type"];
        consultList.noread = [rs stringForColumn:@"noread"];
        consultList.username = [rs stringForColumn:@"username"];
        consultList.method = [rs stringForColumn:@"method"];
        consultList.departmentname=[rs stringForColumn:@"departmentname"];
        consultList.consultType=[rs stringForColumn:@"consultType"];
        [array addObject:consultList];
    }
    [db close];
    return array;
  
}
/**
 *  删除一条咨询记录
 *
 *  @param qid 按照qid来删除
 *
 *  @return 判断删除是否成功
 */
+(BOOL)deleteConsultListWithQid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * myuid = [userDefaults objectForKey:@"SelfUidKey"];
    BOOL success=[db executeUpdate:@"delete from ConsultList where qid=? and myuid=?",qid,myuid];
    [db close];
    return success;
}

/**
 *  安好消息，返回未读的个数
 *
 *  @return 未读个数
 */
+(NSInteger)readUnreadCount
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select count(*) from ConsultList where myuid = %@ and noread=1", uid];
    NSInteger count=[db intForQuery:sql];
    [db close];
    return count;
    
}
/**
 *  获取咨询列表的最后一条数据（按时间排序，即时间是最新的）；
 *
 *  @return 返回最后一条的内容ConsultList类型
 */
+(NSMutableArray *)getTheLastOne
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from ConsultList where myuid = %@ order by dateline desc  limit 0,1", uid];
    FMResultSet *rs=[db executeQuery:sql];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    while ([rs next]) {
        //        NSDictionary *rs=[set resultDictionary];
        ConsultList * consultList = [[ConsultList alloc] init];
        consultList.uid = [rs stringForColumn:@"uid"];
        consultList.date = [rs stringForColumn:@"date"];
        consultList.dateline = [rs stringForColumn:@"dateline"];
        consultList.message = [rs stringForColumn:@"message"];
        consultList.qid = [rs stringForColumn:@"qid"];
        consultList.type = [rs stringForColumn:@"type"];
        consultList.noread = [rs stringForColumn:@"noread"];
        consultList.username = [rs stringForColumn:@"username"];
        consultList.method = [rs stringForColumn:@"method"];
        [array addObject:consultList];
    }
    [db close];
    return array;
}
/**
 *  根据qid和myuid获取咨询列表的左右一条
 *
 *  @return chatlist;
 */
+(NSMutableArray *)getTheLastOneWithQid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from ConsultList where myuid = %@ and qid=%@ order by dateline desc  limit 0,1", uid,qid];
    FMResultSet *rs=[db executeQuery:sql];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    while ([rs next]) {
        //        NSDictionary *rs=[set resultDictionary];
        ConsultList * consultList = [[ConsultList alloc] init];
        consultList.uid = [rs stringForColumn:@"uid"];
        consultList.date = [rs stringForColumn:@"date"];
        consultList.dateline = [rs stringForColumn:@"dateline"];
        consultList.message = [rs stringForColumn:@"message"];
        consultList.qid = [rs stringForColumn:@"qid"];
        consultList.type = [rs stringForColumn:@"type"];
        consultList.noread = [rs stringForColumn:@"noread"];
        consultList.username = [rs stringForColumn:@"username"];
        consultList.method = [rs stringForColumn:@"method"];
        [array addObject:consultList];
    }
    [db close];
    return array;
}
/**
 *  更新咨询（散单被医生回答时），科室和医生名字
 *
 *  @param department 抢答医生的科室名称
 *  @param doctorname 抢答医生的名字
 *  @param qid        咨询时的问题id
 *
 *  @return 是否更新成功，可用于判断；
 */
+(BOOL)refreshTheDepartment:(NSString *)department AndDoctor:(NSString *)doctorname andQid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    NSString * sql = [NSString stringWithFormat:@"update ConsultList set departmentname=?,username=? where qid = ?"];
    BOOL success=[db executeUpdate:sql,department,doctorname,qid];
    [db close];
    return success;

}
@end
